package com.kth.calendar;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ParseException;
import android.widget.Toast;

public class Utility {
	
	static String send(Context context, String url, List<NameValuePair> args, boolean post){
		if(post){
			return postData(context, url, args);
		}else{
			String getArgs = "?";
			for(int i = 0; i < args.size(); i++){
				String arg = args.get(i).getName()+"="+args.get(i).getValue();
				if(i==0){
					getArgs += arg;
				}else{
					getArgs += "&"+arg;
				}
			}
			return getData(context, url, getArgs);
		}
	}
	
	
	// http GET
	static String getData(Context context, String url, String getArgs){
		try{
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url+getArgs);
			HttpResponse http_response = httpClient.execute(httpGet);
			
			return getResponseBody(http_response.getEntity());
		}catch (Exception e) {
			pr(context, "Connection timeout, try again later.");
		}
		return "";
	}
	
	// http POST
    static String postData(Context context, String url, List<NameValuePair> args){
    	HttpClient httpClient = new DefaultHttpClient();
		try{
			HttpPost httpPost = new HttpPost(url);
			HttpParams httpParameters = httpClient.getParams();

			// Set the timeout in milliseconds until a connection is established.
			int timeoutConnection = 60000;
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			// Set the default socket timeout (SO_TIMEOUT) 
			// in milliseconds which is the timeout for waiting for data.
			int timeoutSocket = 60000;
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

			httpClient = new DefaultHttpClient(httpParameters);
			httpPost.setEntity(new UrlEncodedFormEntity(args, "utf-8"));
			HttpResponse response = httpClient.execute(httpPost);
			
			String response_text = getResponseBody(response.getEntity());
			return response_text;
		}catch(ClientProtocolException e){
			pr(context, "http protocol error\n"+e.toString());
		}catch (IOException e) {
			pr(context, "Connection timeout, try again later.");
		}
		return "";
	}
    
    public static String getResponseBody(final HttpEntity entity) throws IOException, ParseException {

		if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
		InputStream instream = entity.getContent();
		if (instream == null) { return ""; }
		if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); }
		String charset = getContentCharSet(entity);
		if (charset == null) {
			charset = HTTP.DEFAULT_CONTENT_CHARSET;
		}
		Reader reader = new InputStreamReader(instream, charset);
		StringBuilder buffer = new StringBuilder();
		try {
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
		} finally {
			reader.close();
		}
		return buffer.toString();
	}
    public static String getContentCharSet(final HttpEntity entity) throws ParseException {
		if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}
		return charset;
	}
    
    public static void pr(Context context, Object o){
		Toast.makeText(context, o+"", Toast.LENGTH_LONG).show();
	}
}
